home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Borland / Borland C++ V5.02 / CMDLG.PAK / CMDLG.C next >
C/C++ Source or Header  |  1997-05-06  |  13KB  |  362 lines

  1. // (C) Copyright 1994 by Borland International
  2. //
  3. // Cmdlg.c - Common Dialogs example in C
  4.  
  5. /*********************************************************************
  6. This program demonstrates the use of Open, Color, and Font common
  7. dialogs which are available in Windows 3.1, Windows NT, and Windows 95.
  8.  
  9. The main window has menu selections for opening a file, changing the
  10. font and changing the color used for the selected font.  When a file is
  11. selected the name will be displayed on the client area of the window.
  12.  
  13. The files needed to build this program are . . .
  14.  
  15. cmdlg.h         Header file for application
  16. cmdlgr.h           Header file for application and resources
  17. cmdlg.c         Source file for application
  18. cmdlg.rc           Resource file for application
  19.  
  20. For a more thorough treatment of the Open common dialog under Windows 95,
  21. see also \BC5\EXAMPLES\WIN95\COMDLG32.
  22. ***********************************************************************/
  23.  
  24. #include <windowsx.h>
  25. // Contains the necessary headers and definitions for this program
  26. #include "cmdlg.h"
  27.  
  28. /***  Global Variables  ***/
  29. char szName[256];
  30. COLORREF crColor;
  31. HFONT hfFont;
  32. BOOL tfFontLoaded;
  33. HINSTANCE hInst;  // current instance
  34.  
  35.  
  36. /*********************************************************************
  37. Using the OPENFILENAME structure and the Windows API call GetOpenFileName()
  38. eases the selection of files for the programmer and for the user.  The
  39. help file WIN31WH.HLP (found in the \BC5\HELP directory) contains a
  40. detailed description of the function call and its associated structure.
  41. The Flags field of the structure is particularly useful when
  42. customization is required.
  43. **********************************************************************/
  44. void CMUFileOpen( HWND hWnd )
  45. {
  46.   OPENFILENAME ofnTemp;
  47.   DWORD Errval; // Error value
  48.   char buf[5];  // Error buffer
  49.   char Errstr[50]="GetOpenFileName returned Error #";
  50.   char szTemp[] = "All Files (*.*)\0*.*\0Text Files (*.txt)\0*.txt\0";
  51. /*
  52. Note the initialization method of the above string.  The GetOpenFileName()
  53. function expects to find a string in the OPENFILENAME structure that has
  54. a '\0' terminator between strings and an extra '\0' that terminates the
  55. entire filter data set.  Using the technique shown below will fail because
  56. "X" is really 'X' '\0' '\0' '\0' in memory.  When the GetOpenFileName()
  57. function scans szTemp it will stop after finding the extra trailing '\0'
  58. characters.
  59.  
  60.   char szTemp[][4] = { "X", "*.*", "ABC", "*.*", "" };
  61.  
  62. The string should be "X\0*.*\0ABC\0*.*\0".
  63.  
  64. Remember that in C or C++ a quoted string is automatically terminated with
  65. a '\0' character so   char "X\0";   would result in 'X' '\0' '\0' which
  66. provides the extra '\0' that GetOpenFileName() needs to see in order to
  67. terminate the scan of the string.  Just 'char ch "X";' would result in 'X'
  68. '\0' and GetOpenFileName() would wander off in memory until it lucked into
  69. a '\0' '\0' character sequence.
  70. */
  71.  
  72. /*
  73. Some Windows structures require the size of themselves in an effort to
  74. provide backward compatibility with future versions of Windows.  If the
  75. lStructSize member is not set the call to GetOpenFileName() will fail.
  76. */
  77.   ofnTemp.lStructSize = sizeof( OPENFILENAME );
  78.   ofnTemp.hwndOwner = hWnd; // An invalid hWnd causes non-modality
  79.   ofnTemp.hInstance = 0;
  80.   ofnTemp.lpstrFilter = (LPSTR)szTemp;  // See previous note concerning string
  81.   ofnTemp.lpstrCustomFilter = NULL;
  82.   ofnTemp.nMaxCustFilter = 0;
  83.   ofnTemp.nFilterIndex = 1;
  84.   ofnTemp.lpstrFile = (LPSTR)szName;  // Stores the result in this variable
  85.   ofnTemp.nMaxFile = sizeof( szName );
  86.   ofnTemp.lpstrFileTitle = NULL;
  87.   ofnTemp.nMaxFileTitle = 0;
  88.   ofnTemp.lpstrInitialDir = NULL;
  89.   ofnTemp.lpstrTitle = "Open";  // Title for dialog
  90.   ofnTemp.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
  91.   ofnTemp.nFileOffset = 0;
  92.   ofnTemp.nFileExtension = 0;
  93.   ofnTemp.lpstrDefExt = "*";
  94.   ofnTemp.lCustData = 0L;
  95.   ofnTemp.lpfnHook = NULL;
  96.   ofnTemp.lpTemplateName = NULL;
  97. /*
  98. If the call to GetOpenFileName() fails you can call CommDlgExtendedError()
  99. to retrieve the type of error that occured.
  100. */
  101.   if(GetOpenFileName( &ofnTemp ) != TRUE)
  102.   {
  103.     Errval=CommDlgExtendedError();
  104.     if(Errval!=0) // 0 value means user selected Cancel
  105.     {
  106.       sprintf(buf,"%ld",Errval);
  107.       strcat(Errstr,buf);
  108.       MessageBox(hWnd,Errstr,"WARNING",MB_OK|MB_ICONSTOP);
  109.     }
  110.  
  111.   }
  112.   InvalidateRect( hWnd, NULL, TRUE ); // Repaint to display the new name
  113. }
  114.  
  115. /*************************************************************************
  116. Using the CHOOSECOLOR structure and the Windows API call ChooseColor(),
  117. eases the selection of colors for the programmer and for the user.  The
  118. comments for the File Open dialog regarding the help file and the structure
  119. size also apply to the color dialog.
  120. **************************************************************************/
  121. void CMUColor( HWND hWnd )
  122. {
  123.   CHOOSECOLOR ccTemp;
  124.   COLORREF crTemp[16];  // Important, sometimes unused, array
  125.  
  126.   ccTemp.lStructSize = sizeof( CHOOSECOLOR );
  127.   ccTemp.hwndOwner = hWnd;
  128.   ccTemp.hInstance = 0;
  129.   ccTemp.rgbResult = crColor; // CC_RGBINIT flag makes this the default color
  130. /*
  131. lpCustColors must be set to a valid array of 16 COLORREF's, even if it
  132. is not used.  If it isn't you will probably fail with a GP fault in
  133. COMMDLG.DLL.
  134. */
  135.   ccTemp.lpCustColors = crTemp;
  136.   ccTemp.Flags = CC_PREVENTFULLOPEN | CC_RGBINIT;
  137.   ccTemp.lCustData = 0L;
  138.   ccTemp.lpfnHook = NULL;
  139.   ccTemp.lpTemplateName = NULL;
  140.   if( ChooseColor( &ccTemp ) == TRUE ) crColor = ccTemp.rgbResult;
  141.   InvalidateRect( hWnd, NULL, TRUE );
  142. }
  143.  
  144. /**************************************************************************
  145. Using the CHOOSEFONT structure and the Windows API call ChooseFont()
  146. eases the selection of fonts for the programmer and for the user.  The
  147. comments for the File Open dialog regarding the help file and the structure
  148. size also apply to the font dialog.
  149. ***************************************************************************/
  150. void CMUFont( HWND hWnd )
  151. {
  152. /*
  153. The variables below are static so that multiple calls to the font dialog will
  154. retain previous user selections.
  155. */
  156.   static CHOOSEFONT cfTemp;
  157.   static LOGFONT lfTemp;
  158.  
  159.   if( tfFontLoaded == TRUE )  // cfTemp contains previous selections
  160.   {
  161.     cfTemp.Flags |= CF_INITTOLOGFONTSTRUCT;
  162.     cfTemp.rgbColors = crColor;
  163.   }
  164.   else
  165.   {
  166.     cfTemp.lStructSize = sizeof( CHOOSEFONT );
  167.     cfTemp.hwndOwner = hWnd;
  168.     cfTemp.hDC = 0;
  169.     cfTemp.lpLogFont = &lfTemp; // Store the result here
  170.     cfTemp.Flags = CF_EFFECTS | CF_FORCEFONTEXIST | CF_SCREENFONTS;
  171.     cfTemp.rgbColors = crColor; // Color and font dialogs use the same color
  172.     cfTemp.lCustData = 0L;
  173.     cfTemp.lpfnHook = NULL;
  174.     cfTemp.lpTemplateName = NULL;
  175.     cfTemp.hInstance = 0;
  176.     cfTemp.lpszStyle = NULL;
  177.     cfTemp.nFontType = SCREEN_FONTTYPE;
  178.     cfTemp.nSizeMin = 0;
  179.     cfTemp.nSizeMax = 0;
  180.   }
  181.   if( ChooseFont( &cfTemp ) == TRUE )
  182.   {
  183.     if( tfFontLoaded == TRUE )
  184.       DeleteObject( hfFont );
  185.     crColor = cfTemp.rgbColors;
  186.     hfFont = CreateFontIndirect( &lfTemp );
  187.     tfFontLoaded = TRUE;
  188.   }
  189.   InvalidateRect( hWnd, NULL, TRUE );
  190. }
  191.  
  192. /**********************************************************************/
  193. BOOL InitApplication(HINSTANCE hInstance)
  194. {
  195.   WNDCLASS  wc;
  196.  
  197.   // Fill in window class structure with parameters that describe the
  198.   // main window.
  199.  
  200.   wc.style = CS_HREDRAW | CS_VREDRAW; // Class style(s).
  201.   wc.lpfnWndProc = (long (FAR PASCAL*)())MainWndProc; // Function to retrieve messages for
  202.                             // windows of this class.
  203.   wc.cbClsExtra = 0;  // No per-class extra data.
  204.   wc.cbWndExtra = 0;  // No per-window extra data.
  205.   wc.hInstance = hInstance; // Application that owns the class.
  206.   wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  207.   wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  208.   wc.hbrBackground = GetStockObject(WHITE_BRUSH);
  209.   wc.lpszMenuName = "CMDLGAPMENU";  // Name of menu resource in .RC file.
  210.   wc.lpszClassName = "CMDLG"; // Name used in call to CreateWindow.
  211.  
  212.   /* Register the window class and return success/failure code. */
  213.  
  214.   return (RegisterClass(&wc));
  215.  
  216. }
  217.  
  218.  
  219. /************************************************************************/
  220. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  221. {
  222.   HWND  hWnd; // Main window handle.
  223.  
  224.   /* Save the instance handle in static variable, which will be used in  */
  225.   /* many subsequence calls from this application to Windows.            */
  226.  
  227.   hInst = hInstance;
  228.  
  229.   /* Create a main window for this application instance.  */
  230.  
  231.   hWnd = CreateWindow(
  232.     "CMDLG",                 // See RegisterClass() call.
  233.     "Common Dialog Example",  // Text for window title bar.
  234.     WS_OVERLAPPEDWINDOW,        // Window style.
  235.     CW_USEDEFAULT,         // Default horizontal position.
  236.     CW_USEDEFAULT,          // Default vertical position.
  237.     CW_USEDEFAULT,            // Default width.
  238.     CW_USEDEFAULT,        // Default height.
  239.     NULL,                  // Overlapped windows have no parent.
  240.     NULL,                  // Use the window class menu.
  241.     hInstance,              // This instance owns this window.
  242.     NULL                   // Pointer not needed.
  243.   );
  244.  
  245.   /* If window could not be created, return "failure" */
  246.  
  247.   if (!hWnd)
  248.     return (FALSE);
  249.  
  250.   /* Make the window visible; update its client area; and return "success" */
  251.  
  252.   ShowWindow(hWnd, nCmdShow); // Show the window
  253.   UpdateWindow(hWnd);     // Sends WM_PAINT message
  254.   return (TRUE);        // Returns the value from PostQuitMessage
  255.  
  256. }
  257.  
  258.  
  259. /****************************************************************************
  260.   FUNCTION: MainWndProc(HWND, UINT, WPARAM, LPARAM)
  261. ****************************************************************************/
  262. LRESULT FAR PASCAL _export MainWndProc(HWND hWnd, UINT message,
  263.                   WPARAM wParam, LPARAM lParam)
  264. {
  265.   HFONT fTemp = (HFONT)NULL;  // Placeholder for the original font
  266.   RECT rTemp;                 // Client are needed by DrawText()
  267.   HDC hdc;                    // HDC for Window
  268.   PAINTSTRUCT ps;             // Paint Struct for BeginPaint call
  269.  
  270.   switch (message) {
  271.   case WM_CREATE: // Initialize Global vars
  272.       strcpy( szName, "" );           // Empty the file name string
  273.       crColor = RGB( 0, 0, 0 );       // Use black as the default color
  274.       hfFont = 0;                     // Empty the handle to the font
  275.       tfFontLoaded = FALSE;           // Set the font selected flag to false
  276.     return 0L;
  277.  
  278.   case WM_PAINT:
  279.   // Display the file name using the selected font in the selected color.
  280.  
  281.       hdc=BeginPaint(hWnd,&ps);
  282.       SetTextColor( hdc, crColor );
  283.       if( tfFontLoaded == TRUE )
  284.         fTemp = (HFONT)SelectObject( hdc, hfFont );
  285.       GetClientRect( hWnd, &rTemp );
  286.       DrawText( hdc, szName, strlen( szName ), &rTemp, DT_CENTER | DT_WORDBREAK );
  287.       if( tfFontLoaded == TRUE )
  288.         SelectObject( hdc, fTemp );
  289.       EndPaint(hWnd,&ps);
  290.     break;
  291.  
  292.   case WM_COMMAND:  // message: command from application menu
  293.     switch(GET_WM_COMMAND_ID(wParam, lParam))
  294.     {
  295.       case CM_EXIT:
  296.           DestroyWindow(hWnd);
  297.         break;
  298.  
  299.       case CM_U_FILEOPEN:
  300.           CMUFileOpen(hWnd);
  301.         break;
  302.  
  303.       case CM_U_COLOR:
  304.           CMUColor(hWnd);
  305.         break;
  306.  
  307.       case CM_U_FONT:
  308.           CMUFont(hWnd);
  309.         break;
  310.  
  311.       case CM_U_HELPABOUT:
  312.           MessageBox(hWnd,szCMDLGAPAbout,"About CMDLG",MB_OK);
  313.         break;
  314.  
  315.       default:
  316.         break;
  317.     }
  318.     break;
  319.  
  320.   case WM_QUIT:
  321.   case WM_DESTROY:  // message: window being destroyed
  322.       if( hfFont != 0 )
  323.         DeleteObject( hfFont );
  324.       PostQuitMessage(0);
  325.     break;
  326.  
  327.   default:      // Passes it on if unproccessed
  328.     return (DefWindowProc(hWnd, message, wParam, lParam));
  329.   }
  330.   return 0L;
  331. }
  332.  
  333. #pragma argsused
  334. /**************************************************************/
  335. int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  336.            LPSTR lpCmdLine, int nCmdShow)
  337. {
  338.   MSG msg;      // message
  339.   if (!hPrevInstance) // Other instances of app running?
  340.   if (!InitApplication(hInstance))  // Initialize shared things
  341.     return (FALSE); // Exits if unable to initialize
  342.  
  343.   /* Perform initializations that apply to a specific instance */
  344.  
  345.   if (!InitInstance(hInstance, nCmdShow))
  346.     return (FALSE);
  347.  
  348.   /* Acquire and dispatch messages until a WM_QUIT message is received. */
  349.  
  350.   while (GetMessage(&msg, // message structure
  351.     NULL, // handle of window receiving the message
  352.     0,    // lowest message to examine
  353.     0))   // highest message to examine
  354.   {
  355.   TranslateMessage(&msg); // Translates virtual key codes
  356.   DispatchMessage(&msg);  // Dispatches message to window
  357.   }
  358.   return (msg.wParam);  // Returns the value from PostQuitMessage
  359. }
  360.  
  361. // End of file cmdlg.c
  362.